package com.yang.config;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.yang.utils.info.AlipayBean;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付配置类
 */
@Configuration
public class AlipayConfig {

    @Resource
    private AlipayBean alipayBean;

    /**
     * 获取支付服务器
     * @return
     */
    @Bean
    public AlipayClient alipayClient() {
        return new DefaultAlipayClient(alipayBean.getUrl(),alipayBean.getAppID(),alipayBean.getRsaPrivateKey(),
                alipayBean.getFormat(),alipayBean.getCharset(),alipayBean.getAliPayPublicKey(), alipayBean.getSingType());
    }

    /**
     * sdk签名验证
     *
     * @param request
     * @return
     */
    public boolean checkSign(HttpServletRequest request) {
        Map<String, String> paramMap = getParams(request);
        //调用sdk签名验证
        try {
            return AlipaySignature.rsaCheckV1(paramMap, alipayBean.getAliPayPublicKey(), alipayBean.getCharset(),
                    alipayBean.getSingType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("===========验签失败===============");
            return false;
        }
    }

    /**
     * 获取request参数
     *
     * @param request
     * @return
     */
    public Map<String, String> getParams(HttpServletRequest request) {
        Map<String, String[]> requestMap = request.getParameterMap();
        Map<String, String> paramMap = new HashMap<>();
        requestMap.forEach((key, values) -> {
            String strs = "";
            for (String value : values) {
                strs += value;
                System.out.println("key:"+key+"====>"+value);
            }
            paramMap.put(key, strs);
        });
        return paramMap;
    }
}
